﻿using Newtonsoft.Json.Linq;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EnterpriseInformation.Common
{
    
    public  class BackService: CustomLog
    {
        public static List<UserHelper> userHelperList = new List<UserHelper>();

        public BackService() {
            InitLog("BackService");
        }
        public static void Start() 
        {
            //读取配置文件
            //loadUserInfo();

            //30分钟检查一次
            //intervalThread(checkUserStatus, 5 * 60 * 1000); 


        }


        /// <summary>
        /// 从本地配置文件中读取信息
        /// </summary>
        public static void loadUserInfo()
        {
            try
            {
                Log.Logger.Information("loadUserInfo......");
                StreamReader reader = new StreamReader("./appsettings.json", Encoding.UTF8);

                string data = reader.ReadToEnd();

                JObject jobj = JObject.Parse(data);

                MyConfig.WebHelperApi = jobj["api"].ToString();

                MyConfig.ProxySetting = JObject.Parse(jobj["proxy"].ToString());

                JArray userList = (JArray)jobj["userlist"];

                //new Thread(() => {

                try
                {
                    foreach (JObject userItem in userList)
                    {
                        string username = userItem["username"].ToString();
                        string password = userItem["password"].ToString();

                        UserHelper userHelper = new UserHelper()
                        {

                            UserName = username,
                            PassWord = password
                        };

                        HttpUtil httpUtil = new HttpUtil(userHelper);

                        ResultModel resultInit = httpUtil.InitIndex();

                        if (!resultInit.Passed)
                        {
                            continue;
                        }

                        ResultModel resultLogin = httpUtil.Login();

                        if (!resultLogin.Passed)
                        {
                            Log.Logger.Information("add " + userHelper.UserName + resultLogin.Html + resultLogin.Message + " no succuss");

                            continue;
                        }
                        Log.Logger.Information("add......" + userHelper.UserName);

                        userHelperList.Add(userHelper);


                    }

                }
                catch (Exception)
                {


                }

                //}).Start();

            }
            catch (Exception)
            {


            }

        }


        /// <summary>
        /// 开启线程定时器
        /// </summary>
        /// <param name="action"></param>
        /// <param name="interval"></param>
        public static void intervalThread(Action action, double interval)
        {
            new Thread(() => {

                //自执行一次
                //action(); 

                System.Timers.Timer timerThread = new System.Timers.Timer(interval);
                timerThread.Elapsed +=
                new System.Timers.ElapsedEventHandler((_sender, _e) =>
                {
                    action();
                });

                timerThread.AutoReset = true;
                timerThread.Enabled = true;

            }).Start();

        }

        public static void checkUserStatus()
        {

            try
            {

                if (userHelperList == null || userHelperList.Count < 1)
                {
                    return;
                }


                foreach (UserHelper userHelper in userHelperList)
                {
                    try
                    {
                        HttpUtil httpUtil = new HttpUtil(userHelper);

                        ResultModel resultInit = httpUtil.InitIndex();

                        if (!resultInit.Passed)
                        {
                            continue;
                        }

                        if (!resultInit.Html.Contains(userHelper.UserName) || resultInit.Html.Replace(" ", "").Contains("登录|注册") )
                        {
                            //离线了
                            ResultModel resultLogin = httpUtil.Login();

                            if (!resultLogin.Passed)
                            {
                                continue;
                            } 

                        } 
                    }
                    catch (Exception)
                    {

                        
                    }
                }
                userHelperList = userHelperList.Where(p => !string.IsNullOrEmpty(p.MyCookie)).ToList() ;
            }
            catch (Exception)
            {
            }

        }



    }


}
